package com.hjq.bar;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ElementScatter;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * TitleBar.
 *
 * @since 2021-08-22
 */
public class TitleBar extends StackLayout {
  private static String sGlobalStyle;
  private Text leftText;
  private Button centreText;
  private Component bottomLine;
  private Image rightImg;
  private Text rightText;
  private DirectionalLayout titleView;
  private DirectionalLayout rightView;
  private DirectionalLayout leftView;
  private Image leftImg;
  private final int DEFAULT_TEXT_SIZE = 14;
  private final int DEFAULT_ICON_SIZE = 50;
  private String mCurrentStyle;
  private OnTitleBarListener mListener;
  private int mDrawableSize;
  private int mHorizontalPadding;
  private int mVerticalPadding;

  /**
   * TitleBar.
   *
   * @param context context
   */
  public TitleBar(Context context) {
    this(context, null);
  }

  /**
   * TitleBar.
   *
   * @param context context
   * @param attrSet attrSet
   */
  public TitleBar(Context context, AttrSet attrSet) {
    super(context, attrSet);
    Component component = LayoutScatter.getInstance(context)
        .parse(ResourceTable.Layout_layout_titlebar, null, false);

    if (sGlobalStyle == null) {
      sGlobalStyle = "light";
    }

    // 左布局
    leftView = (DirectionalLayout) component.findComponentById(ResourceTable.Id_left_bank_dil);
    leftView.setClickedListener(component1 -> {
      if (mListener != null) {
        mListener.onLeftClick(component1);
      }
    });
    leftText = (Text) component.findComponentById(ResourceTable.Id_left_bank_text);
    leftImg = (Image) component.findComponentById(ResourceTable.Id_left_bank_button);
    // 中布局
    titleView = (DirectionalLayout) component.findComponentById(ResourceTable.Id_center_del);
    centreText = (Button) component.findComponentById(ResourceTable.Id_centre_title_ButtonText);
    centreText.setClickedListener(component1 -> {
      if (mListener != null) {
        mListener.onTitleClick(component);
      }
    });
    // 右布局
    rightView = (DirectionalLayout) component.findComponentById(ResourceTable.Id_right_del);
    rightView.setClickedListener(component1 -> {
      if (mListener != null) {
        mListener.onRightClick(component);
      }
    });
    rightText = (Text) component.findComponentById(ResourceTable.Id_right_text_qd);
    rightImg = (Image) component.findComponentById(ResourceTable.Id_right_message_img);
    // 底部线
    bottomLine = component.findComponentById(ResourceTable.Id_bottom_line);
    addComponent(component);

    // 左侧返回图片 默认显示
    leftImg.setVisibility(AttrUtils.getBooleanFromAttr(attrSet, "backButton", true)
        ? VISIBLE : HIDE);
    leftImg.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
    rightImg.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
    // 左边返回图标 默认是返回icon
    if (attrSet.getAttr("leftIcon") != null && attrSet.getAttr("leftIcon").isPresent()
        && attrSet.getAttr("leftIcon").get() != null) {
      leftImg.setPixelMap(getPixelMap(AttrUtils.getStringFromAttr(attrSet, "leftIcon",
          null), context));
      leftImg.setHeight(AttrUtils.getDimensionFromAttr(attrSet, "drawableSize",
          AttrHelper.vp2px(DEFAULT_ICON_SIZE, context)));
      leftImg.setWidth(AttrUtils.getDimensionFromAttr(attrSet, "drawableSize",
          AttrHelper.vp2px(DEFAULT_ICON_SIZE, context)));
    } else {
      Element iconElement =
          ElementScatter.getInstance(context).parse(ResourceTable.Graphic_bar_arrows_left_black);
      leftImg.setImageElement(iconElement);
    }
    // 左边
    if (TextTool.isNullOrEmpty(AttrUtils.getStringFromAttr(attrSet, "leftTitle", ""))) {
      leftText.setVisibility(HIDE);
    } else {
      // 左边按钮文字，默认空
      leftText.setText(AttrUtils.getStringFromAttr(attrSet, "leftTitle", ""));
      // 左边按钮文字大小， 默认14
      leftText.setTextSize(AttrUtils.getDimensionFromAttr(attrSet, "leftSize",
          DEFAULT_TEXT_SIZE), Text.TextSizeType.FP);
      // 左边按钮文字颜色， 默认灰色
      leftText.setTextColor(AttrUtils.getColorsFromAttr(attrSet, "leftColor", Color.GRAY));

      // 标题字体样式
      String fontStyle = AttrUtils.getStringFromAttr(attrSet, "titleStyle", "");
      if ("bold".equals(fontStyle)) {
        leftText.setFont(Font.DEFAULT_BOLD);
      } else if ("italic".equals(fontStyle)) {
        leftText.setFont(new Font.Builder("italic").makeItalic(true).build());
      }
    }

    // 中间
    if (TextTool.isNullOrEmpty(AttrUtils.getStringFromAttr(attrSet, "title", ""))) {
      centreText.setVisibility(HIDE);
    } else {
      // 中间按钮文字，默认空
      centreText.setText(AttrUtils.getStringFromAttr(attrSet, "title", ""));
      // 中间按钮文字大小， 默认18
      centreText.setTextSize(AttrUtils.getDimensionFromAttr(attrSet, "titleSize",
          DEFAULT_TEXT_SIZE), Text.TextSizeType.FP);
      // 中间按钮文字颜色， 默认黑色
      centreText.setTextColor(AttrUtils.getColorsFromAttr(attrSet, "titleColor",
          Color.BLACK));
      // 中间跑马灯文字效果
      if (AttrUtils.getBooleanFromAttr(attrSet, "pmdText", false)) {
        centreText.setVisibility(VISIBLE);
        centreText.setTruncationMode(Text.TruncationMode.AUTO_SCROLLING);
        centreText.setAutoScrollingCount(Text.AUTO_SCROLLING_FOREVER);
        centreText.startAutoScrolling();
      }
      // 标题字体样式
      String fontStyle = AttrUtils.getStringFromAttr(attrSet, "titleStyle", "");
      if ("bold".equals(fontStyle)) {
        centreText.setFont(Font.DEFAULT_BOLD);
      } else if ("italic".equals(fontStyle)) {
        centreText.setFont(new Font.Builder("italic").makeItalic(true).build());
      }
    }

    // 右边
    if (TextTool.isNullOrEmpty(AttrUtils.getStringFromAttr(attrSet, "rightTitle", ""))) {
      rightText.setVisibility(HIDE);
    } else {
      // 右边文字，默认为空
      rightText.setText(AttrUtils.getStringFromAttr(attrSet, "rightTitle", ""));
      // 右边文字大小，默认18
      rightText.setTextSize(AttrUtils.getDimensionFromAttr(attrSet, "rightSize",
          DEFAULT_TEXT_SIZE), Text.TextSizeType.FP);
      // 右边文字颜色
      rightText.setTextColor(AttrUtils.getColorsFromAttr(attrSet, "rightColor",
          new Color(Color.GRAY.getValue())));
    }

    // 右边文字布局，默认隐藏
    if (attrSet.getAttr("rightIcon") != null || attrSet.getAttr("rightTitle") != null || attrSet.getAttr("rightTint") != null) {
      rightView.setVisibility(VISIBLE);
    } else {
      rightView.setVisibility(HIDE);
    }
    if (AttrUtils.getElementFromAttr(attrSet, "rightIcon", null) == null) {
      rightImg.setVisibility(HIDE);
    } else {
      // 右边图片
      rightImg.setPixelMap(getPixelMap(AttrUtils.getStringFromAttr(attrSet, "rightIcon",
          null), context));
      // 右边图片大小
      rightImg.setComponentSize(AttrUtils.getDimensionFromAttr(attrSet, "drawableSize",
          AttrHelper.vp2px(DEFAULT_ICON_SIZE, context)), AttrUtils.getDimensionFromAttr(attrSet,
          "drawableSize", AttrHelper.vp2px(DEFAULT_ICON_SIZE, context)));
    }

    // 底部边线,默认显示  lineVisible
    bottomLine.setVisibility(AttrUtils.getBooleanFromAttr(attrSet, "lineVisible", true) ?
        VISIBLE : INVISIBLE);

    // barStyle
    ShapeElement shapeElement = new ShapeElement();
    if (attrSet.getAttr("barStyle") != null && attrSet.getAttr("barStyle").isPresent() && attrSet.getAttr("barStyle").get() != null) {
      String barStyle = AttrUtils.getStringFromAttr(attrSet, "barStyle", "");
      mCurrentStyle = barStyle;
      if ("light".equals(barStyle)) {
        // 整个布局背景颜色
        shapeElement.setRgbColor(RgbColor.fromArgbInt(0x00000000));
        leftText.setTextColor(new Color(0xFF666666));
        centreText.setTextColor(new Color(0xFF222222));
        rightText.setTextColor(new Color(0xFFA4A4A4));
      } else if ("night".equals(barStyle)) {
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.BLACK.getValue()));
        leftText.setTextColor(new Color(0xCCFFFFFF));
        centreText.setTextColor(new Color(0xEEFFFFFF));
        rightText.setTextColor(new Color(0xCCFFFFFF));
        Element iconElement =
            ElementScatter.getInstance(context).parse(ResourceTable.Graphic_bar_arrows_left_white);
        leftImg.setImageElement(iconElement);
      } else if ("transparent".equals(barStyle)) {
        shapeElement.setRgbColor(RgbColor.fromArgbInt(0x00000000));
        leftText.setTextColor(new Color(0xFFFFFFFF));
        centreText.setTextColor(new Color(0xFFFFFFFF));
        rightText.setTextColor(new Color(0xFFFFFFFF));
        Element iconElement =
            ElementScatter.getInstance(context).parse(ResourceTable.Graphic_bar_arrows_left_white);
        leftImg.setImageElement(iconElement);
      } else if ("ripple".equals(barStyle)) {
        shapeElement.setRgbColor(RgbColor.fromArgbInt(0x00000000));
        leftText.setTextColor(new Color(0xCCFFFFFF));
        centreText.setTextColor(new Color(0xEEFFFFFF));
        rightText.setTextColor(new Color(0xCCFFFFFF));
        Element iconElement =
            ElementScatter.getInstance(context).parse(ResourceTable.Graphic_bar_arrows_left_white);
        leftImg.setImageElement(iconElement);
      }
    } else {
      shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.WHITE.getValue()));
    }
    component.setBackground(shapeElement);
  }

  /**
   * 设置监听器.
   */
  public TitleBar setOnTitleBarListener(OnTitleBarListener listener) {
    mListener = listener;
    return this;
  }

  /**
   * 设置标题.
   */
  public TitleBar setTitle(String text) {
    centreText.setText(text);
    return this;
  }

  /**
   * 获取标题.
   */
  public String getTitle() {
    return centreText.getText();
  }

  /**
   * 设置左标题.
   */
  public TitleBar setLeftTitle(String text) {
    leftText.setText(text);
    return this;
  }

  /**
   * 获取左标题.
   */
  public String getLeftTitle() {
    return leftText.getText();
  }

  /**
   * 设置右标题.
   */
  public TitleBar setRightTitle(String text) {
    rightText.setText(text);
    return this;
  }

  /**
   * 获取右标题.
   */
  public String getRightTitle() {
    return rightText.getText();
  }

  /**
   * 设置左图标.
   */
  public TitleBar setLeftIcon(int resource) {
    Resource mResource;
    try {
      mResource = getResourceManager().getResource(resource);
      PixelMap pixelmap = ImageSource.create(mResource, null).createPixelmap(null);
      leftImg.setPixelMap(pixelmap);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return this;
  }

  /**
   * 设置左图标色彩.
   */
  public TitleBar setLeftTint(int color) {
    return this;
  }

  /**
   * 获取左图标.
   */
  public Element getLeftIcon() {
    return leftImg.getImageElement();
  }

  /**
   * 设置右图标.
   */
  public TitleBar setRightIcon(int resource) {
    Resource mResource;
    try {
      mResource = getResourceManager().getResource(resource);
      PixelMap pixelmap = ImageSource.create(mResource, null).createPixelmap(null);
      rightImg.setPixelMap(pixelmap);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return this;
  }

  /**
   * 设置右图标色彩.
   */
  public TitleBar setRightTint(int color) {
    return this;
  }

  /**
   * 获取右图标.
   */
  public Element getRightIcon() {
    return rightImg.getImageElement();
  }

  /**
   * 设置标题颜色.
   */
  public TitleBar setTitleColor(int color) {
    centreText.setTextColor(new Color(color));
    return this;
  }

  /**
   * 设置左标题颜色.
   */
  public TitleBar setLeftColor(int color) {
    leftText.setTextColor(new Color(color));
    return this;
  }

  /**
   * 设置右标题颜色.
   */
  public TitleBar setRightColor(int color) {
    rightText.setTextColor(new Color(color));
    return this;
  }

  /**
   * 设置右标题状态选择器.
   */
  public TitleBar setRightBackground(int id) {
    return this;
  }

  /**
   * 设置标题文字大小.
   */
  public TitleBar setTitleSize(int size, Text.TextSizeType textSizeType) {
    centreText.setTextSize(size, textSizeType);
    return this;
  }

  /**
   * 设置左标题文字大小.
   */
  public TitleBar setLeftSize(int size, Text.TextSizeType textSizeType) {
    leftText.setTextSize(size, textSizeType);
    return this;
  }

  /**
   * 设置右标题文字大小.
   */
  public TitleBar setRightSize(int size, Text.TextSizeType textSizeType) {
    rightText.setTextSize(size, textSizeType);
    return this;
  }

  /**
   * 设置分割线是否显示.
   */
  public TitleBar setLineVisible(boolean visible) {
    bottomLine.setVisibility(visible ? VISIBLE : INVISIBLE);
    return this;
  }

  /**
   * 设置分割线的颜色.
   */
  public TitleBar setLineDrawable(Element element) {
    bottomLine.setBackground(element);
    return this;
  }

  /**
   * 设置分割线的大小.
   */
  public TitleBar setLineSize(int px) {
    ComponentContainer.LayoutConfig layoutParams = bottomLine.getLayoutConfig();
    layoutParams.height = px;
    bottomLine.setLayoutConfig(layoutParams);
    return this;
  }

  /**
   * 设置标题重心.
   */
  public TitleBar setTitleGravity(int gravity) {
    return this;
  }

  /**
   * 设置标题文字样式.
   */
  public TitleBar setTitleStyle(Font font) {
    centreText.setFont(font);
    return this;
  }

  /**
   * 设置图标显示大小.
   */
  public TitleBar setDrawableSize(int px) {
    mDrawableSize = px;
    leftImg.setWidth(px);
    leftImg.setHeight(px);
    rightImg.setWidth(px);
    rightImg.setHeight(px);
    return this;
  }

  /**
   * 设置文字和图标的间距.
   */
  public TitleBar setDrawablePadding(int padding) {
    leftText.setPaddingLeft(padding);
    rightText.setPaddingRight(padding);
    return this;
  }

  /**
   * 设置子 View 内间距.
   */
  public TitleBar setChildPadding(int horizontalPadding, int verticalPadding) {
    mHorizontalPadding = horizontalPadding;
    mVerticalPadding = verticalPadding;
    leftView.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);
    titleView.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);
    rightView.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);
    return this;
  }

  /**
   * 获取左标题View对象.
   */
  public Text getLeftView() {
    return leftText;
  }

  /**
   * 获取标题View对象.
   */
  public Text getTitleView() {
    return centreText;
  }

  /**
   * 获取右标题View对象.
   */
  public Text getRightView() {
    return rightText;
  }

  /**
   * 获取分割线View对象.
   */
  public Component getLineView() {
    return bottomLine;
  }

  /**
   * 获取当前的初始化器.
   */
  public String getCurrentStyle() {
    return mCurrentStyle;
  }

  /**
   * 设置默认初始化器.
   */
  public static void setDefaultStyle(String style) {
    sGlobalStyle = style;
  }

  /**
   * 通过资源ID获取位图对象.
   **/
  private PixelMap getPixelMap(String mediaId, Context context) {
    ResourceManager resourceManager = context.getResourceManager();
    ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
    sourceOptions.formatHint = "image/gif";
    Pattern pattern = Pattern.compile("[^0-9]");
    Matcher matcher = pattern.matcher(mediaId);
    String all = matcher.replaceAll("");
    RawFileEntry rawFileEntry;
    PixelMap pixelmap;
    try {
      rawFileEntry =
          resourceManager.getRawFileEntry(resourceManager.getMediaPath(Integer.parseInt(all)));
      pixelmap = ImageSource.create(rawFileEntry.openRawFile(), null).createPixelmap(null);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    return pixelmap;
  }
}
